package com.example.wpx.service.impl;

import com.example.wpx.dao.UserMapper;
import com.example.wpx.pojo.User;
import com.example.wpx.service.EntrustSerivice;
import com.example.wpx.service.UserService;
import com.example.wpx.util.EmptyUtil;
import com.example.wpx.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Override
    public User selectByPrimaryKey(Integer id) {
        return  userMapper.selectByPrimaryKey(id);
    }

    public boolean checkPhone(String phone){
        if(userMapper.checkPhone(phone)>0){
            return true;
        }
        return false;
    }

    public static String md5(String plainText) {
        //定义一个字节数组
        byte[] secretBytes = null;
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            //对字符串进行加密
            md.update(plainText.getBytes());
            //获得加密后的数据
            secretBytes = md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        //将加密后的数据转换为16进制数字
        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
        // 如果生成数字未满32位，需要前面补0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }


    @Override
    public ServerResponse reg(String phone, String pwd) {

        if(EmptyUtil.isEmpty(phone) || EmptyUtil.isEmpty(pwd) || !phone.startsWith("1") || phone.length()!=11 ){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        if(checkPhone(phone)){
            return ServerResponse.createByErrorMessage("手机号已注册");
        }
        User user = new User();
        user.setPhone(phone);
        user.setWpd(md5(pwd));
        int index = userMapper.insertSelective(user);
        if(index>0){
            return  ServerResponse.createBySuccessMessage("注册成功");
        }
        return ServerResponse.createByErrorMessage("注册失败");
    }

    @Override
    public ServerResponse log(String phone, String pwd) {
        if(EmptyUtil.isEmpty(phone) || EmptyUtil.isEmpty(pwd) || !phone.startsWith("1") || phone.length()!=11 ){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        User user = userMapper.selectByPrimaryPhone(phone);
        if(EmptyUtil.isEmpty(user)){
            return ServerResponse.createByErrorMessage("手机号未注册，请注册后再来吧");
        }
        if(md5(pwd).equals(user.getWpd())){
            user.setName(EmptyUtil.isEmpty(user.getName())?"":user.getName());
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMessage("用户名或密码错误");
    }
}
